#!/usr/bin/env python3
# encoding: utf-8

"""
@version: 1.0
@author: 周永波
@file: database.py.py
@time: 2020/8/12 14:44
"""
import logging

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from demoApp.util.appUtils import dict_get

db: SQLAlchemy = None
log = logging.getLogger(__name__)

def init_db_app(name, db_app):
    if name == 'db':
        global db
        db = db_app

# def db()->SQLAlchemy:
#     return db

class data_db:

    def __init__(self, app: Flask, property={}):
        self.app = app
        self.db_type = dict_get(property, ['type'])
        self.user = dict_get(property, ['user'])
        self.password = dict_get(property, ['password'])
        self.url = dict_get(property, ['url'])
        self.db = None
        self.matching_db()

    def matching_db(self):
        db_type_get = {'mysql': self.mysql_db, 'oracle': self.oracle}
        type_func = dict_get(db_type_get, [self.db_type])
        if type_func is None:
            raise Exception('数据库类型错误')
        type_func()

    def mysql_db(self):
        # 指定数据库的链接信息
        self.app.config[
            "SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://" + self.user + ":" + self.password + "@" + self.url
        # 这个配置将来会被禁用,设置为True或者False可以解除警告信息,建议设置False
        self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
        self.db = SQLAlchemy(self.app)

    def oracle(self):
        # 指定数据库的链接信息
        self.app.config[
            "SQLALCHEMY_DATABASE_URI"] = "oracle+cx_oracle://" + self.user + ":" + self.password + "@" + self.url
        # 这个配置将来会被禁用,设置为True或者False可以解除警告信息,建议设置False
        self.app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
        self.db = SQLAlchemy(self.app)
